package com.elong.businesstravel.base.recorder;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.dialog.CustomDialogView;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.recorder.Recorder;
import com.elong.businesstravel.base.recorder.RemainingTimeCalculator;
import com.elong.businesstravel.base.recorder.VUMeter;
import com.elong.businesstravel.base.recorder.listener.IRecordingListener;
import com.elong.businesstravel.base.recorder.listener.IRecordingStateListener;
import com.elong.businesstravel.base.recorder.listener.RecordOnTouchListener;

public class BaseRecordActivity extends BaseActivity implements
		Recorder.OnStateChangedListener, IRecordingListener,
		SensorEventListener {

	private CustomDialogView mCustomDialogView;

	RemainingTimeCalculator mRemainingTimeCalculator;
	Recorder mRecorder;
	boolean mSampleInterrupted = false;
	String mErrorUiMessage = null; // Some error messages are displayed in the
									// UI,
									// not a dialog. This happens when a
									// recording
									// is interrupted for some reason.
	long mMaxFileSize = -1; // can be specified in the intent

	static final String TAG = "SoundRecorder";
	static final String STATE_FILE_NAME = "soundrecorder.state";
	static final String RECORDER_STATE_KEY = "recorder_state";
	static final String SAMPLE_INTERRUPTED_KEY = "sample_interrupted";
	static final String MAX_FILE_SIZE_KEY = "max_file_size";

	static final String AUDIO_3GPP = "audio/3gpp";
	static final String AUDIO_AMR = "audio/amr";
	static final String AUDIO_ANY = "audio/*";
	static final String ANY_ANY = "*/*";

	static final int BITRATE_AMR = 5900; // bits/sec
	static final int BITRATE_3GPP = 5900;

	private WakeLock mWakeLock;
	private String mRequestedType = AUDIO_AMR;

	private String mTimerFormat;

	private BaseMeterImageView mVUMeter;
	private BroadcastReceiver mSDCardMountEventReceiver = null;

	/*** 切换扬声器 */
	private AudioManager audioManager = null; // 声音管理器
	private SensorManager _sensorManager = null; // 传感器管理器
	private Sensor mProximiny = null; // 传感器实例
	private float f_proximiny; // 当前传感器距离

	@Override
	protected void onCreate(Bundle icycle) {
		super.onCreate(icycle);

		Intent i = getIntent();
		if (i != null) {

			final String EXTRA_MAX_BYTES = android.provider.MediaStore.Audio.Media.EXTRA_MAX_BYTES;
			mMaxFileSize = i.getLongExtra(EXTRA_MAX_BYTES, -1);
		}

		mRecorder = new Recorder();
		mRecorder.setRecordMinLenght(5);//s
		mRecorder.setOnStateChangedListener(this);
		mRemainingTimeCalculator = new RemainingTimeCalculator();

		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
				"SoundRecorder");

		registerExternalStorageListener();
		if (icycle != null) {
			Bundle recorderState = icycle.getBundle(RECORDER_STATE_KEY);
			if (recorderState != null) {
				mRecorder.restoreState(recorderState);
				mSampleInterrupted = recorderState.getBoolean(
						SAMPLE_INTERRUPTED_KEY, false);
				mMaxFileSize = recorderState.getLong(MAX_FILE_SIZE_KEY, -1);
			}
		}

		updateUi();

		// 利用手机距离感应器来切换是用扬声器听音乐还是听筒听音乐
		audioManager = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		_sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mProximiny = _sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		if (mRecorder.sampleLength() == 0)
			return;

		Bundle recorderState = new Bundle();

		mRecorder.saveState(recorderState);
		recorderState.putBoolean(SAMPLE_INTERRUPTED_KEY, mSampleInterrupted);
		recorderState.putLong(MAX_FILE_SIZE_KEY, mMaxFileSize);

		outState.putBundle(RECORDER_STATE_KEY, recorderState);
	}

	/*
	 * Registers an intent to listen for ACTION_MEDIA_EJECT/ACTION_MEDIA_MOUNTED
	 * notifications.
	 */
	private void registerExternalStorageListener() {
		if (mSDCardMountEventReceiver == null) {
			mSDCardMountEventReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					String action = intent.getAction();
					if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
						// 已拔掉外部大容量储存设备发出的广播（比如SD卡，或移动硬盘）,不管有没有正确卸载都会发出此广播?
						// 广播：用户想要移除扩展介质（拔掉扩展卡）。
						mRecorder.delete();
					} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
						// 插入SD卡并且已正确安装（识别）时发出的广播
						// 广播：扩展介质被插入，而且已经被挂载。
						mSampleInterrupted = false;
						updateUi();
					}
				}
			};
			IntentFilter iFilter = new IntentFilter();
			iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
			iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
			iFilter.addDataScheme("file");
			registerReceiver(mSDCardMountEventReceiver, iFilter);
		}
	}

	/**
	 * 
	 * @param meterImageView
	 *            显示录音音量大小的ImageView
	 * @param recorderView
	 *            按住录音的view
	 * @param iRecordingStateListener
	 *            状态监听
	 */
	public void setBaseMeterImageView(BaseMeterImageView meterImageView,
			View recorderView, IRecordingStateListener iRecordingStateListener) {

		mVUMeter = meterImageView;
		mVUMeter.setRecorder(mRecorder);
		recorderView.setOnTouchListener(new RecordOnTouchListener(mContext,
				mCustomDialogView, null, recorderView, mRecorder, this,
				iRecordingStateListener));

	}

	public void customDialogView(View recorderView) {

		mCustomDialogView = new CustomDialogView(mContext);
		View view = LayoutInflater.from(mContext).inflate(
				R.layout.dialog_voice, null);

		mVUMeter = (VUMeter) view.findViewById(R.id.uvMeter);

		mVUMeter.setRecorder(mRecorder);

		final TextView textView = (TextView) view
				.findViewById(R.id.tipsTextView);
		textView.setText("手指上滑，取消发送");
		textView.setVisibility(View.VISIBLE);
		ViewGroup recordLayout = (ViewGroup) view
				.findViewById(R.id.recordLayout);
		mCustomDialogView.setContentView(view, recordLayout);
		recorderView.setOnTouchListener(new RecordOnTouchListener(mContext,
				mCustomDialogView, view, recorderView, mRecorder, this, null));

	}

	@Override
	protected void onDestroy() {
		if (null != mCustomDialogView)
			mCustomDialogView.removeDialogText();

		unregisterReceiver(mSDCardMountEventReceiver);

		super.onDestroy();
	}

	// 点击录音
	private void record() {

		mRemainingTimeCalculator.reset();
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			mSampleInterrupted = true;
			// mErrorUiMessage =
			// getResources().getString(R.string.insert_sd_card);
			mErrorUiMessage = "请插入SD卡";
			updateUi();
		} else if (!mRemainingTimeCalculator.diskSpaceAvailable()) {
			mSampleInterrupted = true;
			// mErrorUiMessage =
			// getResources().getString(R.string.storage_is_full);
			mErrorUiMessage = "存储卡已满";
			updateUi();
		} else {
			stopAudioPlayback();

			mRemainingTimeCalculator.setBitRate(BITRATE_AMR);
			mRecorder.startRecording(MediaRecorder.OutputFormat.RAW_AMR,
					".amr", this);

			if (mMaxFileSize != -1) {
				mRemainingTimeCalculator.setFileSizeLimit(
						mRecorder.sampleFile(), mMaxFileSize);
			}
		}

	}

	/**
	 * Shows/hides the appropriate child views for the new state.
	 */
	private void updateUi() {
		if (null != mVUMeter) {
			mVUMeter.invalidate();
		}
	}

	/*
	 * Make sure we're not recording music playing in the background, ask the
	 * MediaPlaybackService to pause playback.
	 */
	private void stopAudioPlayback() {
		// Shamelessly copied from MediaPlaybackService.java, which
		// should be public, but isn't.
		Intent i = new Intent("com.android.music.musicservicecommand");
		i.putExtra("command", "pause");

		sendBroadcast(i);
	}

	@Override
	public void onStateChanged(int state) {
		if (state == Recorder.PLAYING_STATE
				|| state == Recorder.RECORDING_STATE) {
			mSampleInterrupted = false;
			mErrorUiMessage = null;
		}

		if (state == Recorder.RECORDING_STATE) {
			mWakeLock.acquire(); // we don't want to go to sleep while recording
		} else {
			if (mWakeLock.isHeld())
				mWakeLock.release();
		}

		updateUi();

	}

	@Override
	public void onError(int error) {
		Resources res = getResources();

		String message = null;
		switch (error) {
		case Recorder.SDCARD_ACCESS_ERROR:
			message = "sdcard无法访问";
			break;
		case Recorder.IN_CALL_RECORD_ERROR:
			// TODO: update error message to reflect that the recording could
			// not be
			// performed during a call.
		case Recorder.INTERNAL_ERROR:
			message = "error_app_internal";
			break;
		}
		if (message != null) {
			new AlertDialog.Builder(this).setTitle(R.string.app_name)
					.setMessage(message).setPositiveButton("确定", null)
					.setCancelable(false).show();
		}

	}

	@Override
	public void onCompletion() {

	}

	@Override
	public void startRecording() {
		record();

	}

	/** 停止录音，准备发送 */
	@Override
	public void stopRecording() {

		if (mRecorder.getRecorderFile() != null) {
			// 发送录音
			sendRecorder(mRecorder);
		} else {
			HandlerToastUI.getHandlerToastUI(mContext, "请检查SD卡是否正常");
		}

	}

	/**
	 * 发送录音
	 * 
	 * @param recorder
	 */
	protected void sendRecorder(Recorder recorder) {

	}

	// 播放录音准备
	public boolean preRecord() {

		mRemainingTimeCalculator.reset();
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			mErrorUiMessage = "请插入SD卡";
			HandlerToastUI.getHandlerToastUI(mContext, mErrorUiMessage);

			return false;
		} else if (!mRemainingTimeCalculator.diskSpaceAvailable()) {
			mErrorUiMessage = "存储卡已满";
			updateUi();
			HandlerToastUI.getHandlerToastUI(mContext, mErrorUiMessage);
			return false;
		}

		return true;
	}

	private void quit() {

		finish();
	}

	// 回退
	public void onBack(View view) {

		quit();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 注册传感器
		_sensorManager.registerListener(this, mProximiny,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 取消注册传感器
		_sensorManager.unregisterListener(this);
		if (null != mRecorder)
			mRecorder.stopPlayback();
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// f_proximiny = event.values[0];
		//
		// if (f_proximiny == mProximiny.getMaximumRange()) {
		// HandlerToastUI.getHandlerToastUI(mContext, "正常模式");
//		 audioManager.setMode(AudioManager.MODE_NORMAL);
		// } else {
		// HandlerToastUI.getHandlerToastUI(mContext, "听筒模式");
		// audioManager.setMode(AudioManager.MODE_IN_CALL);
		// }

	}

}
